import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Row, Col, Card, Statistic, Typography, Modal, message, Descriptions, Select, Image } from 'antd';
import styles from './Index.less';
import { getNoticeList, getUnReadNum, readNotice, getOrderView, getInComeView, getNoticeDetail } from '@/services/user';
import { QuestionCircleOutlined } from '@ant-design/icons';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import moment from 'moment';

const { Title, Paragraph } = Typography;
const { Option } = Select;

const Index: React.FC = () => {

    const actionRef = useRef<ActionType>();
    const [explain_visible, setExplain_visible] = useState<boolean>(false);
    const [notice_visible, setNotice_visible] = useState<boolean>(false);
    const [orderView, setOrderView] = useState<any>();
    const [inComeView, setInComeView] = useState<any>();
    const [unReadNum, setUnReadNum] = useState<number>(0);
    const [readType, setReadType] = useState<number>(0);

    const [noticeDetail, setNoticeDetail] = useState<any>();

    const getUnReadCount = async () => {
        try {
            const msg = await getUnReadNum({ platform: 3 });
            if (msg.code === 0) {
                setUnReadNum(msg.body);
                return;
            }
        } catch (error) {
            message.error(`${error}`);
        }
    }

    const getOrderViewData = async () => {
        try {
            const msg = await getOrderView({ selectDay: 90 });
            if (msg.code === 0) {
                setOrderView(msg.body);
                return;
            }
        } catch (error) {
            message.error(`${error}`);
        }
    }

    const getInComeViewData = async () => {
        try {
            const msg = await getInComeView({});
            if (msg.code === 0) {
                setInComeView(msg.body);
                return;
            }
        } catch (error) {
            message.error(`${error}`);
        }
    }

    useEffect(() => {
        getUnReadCount();
        getOrderViewData();
        getInComeViewData();
    }, []);

    // 获取通知详情
    const getNoticeData = async (id: number, read: number) => {
        try {
            const msg = await getNoticeDetail({ id });
            if (msg.code === 0) {
                setNoticeDetail(msg.body);
                // 判断是否已读
                read === 1 ? handleReadNotice(id) : setNotice_visible(true);;
                return;
            }
        } catch (error) {
            message.error(`${error}`);
        }
    }

    //  标为已读
    const handleReadNotice = async (id: number) => {
        try {
            const msg = await readNotice({ id });
            if (msg.code === 0) {
                setNotice_visible(true);
            }
        } catch (error) {
            message.error(`${error}`);
        }
    }

    const columns: ProColumns<any>[] = [
        {
            title: '状态',
            dataIndex: 'read',
            render: (dom: any, record: any) => {
                return record.read === 1 ? <div style={{ color: 'red' }}>未读</div> : <div style={{ color: 'green' }}>已读</div>;
            }
        },
        {
            title: '通知标题',
            dataIndex: 'title',
            render: (dom: any, record: any) => {
                return <div style={{ cursor: 'pointer' }} onClick={() => {
                    getNoticeData(record.id, record.read);
                }}>{dom}</div>
            }
        },
        {
            title: '发布时间',
            dataIndex: 'createTime',
            width: '120px',
        }
    ];

    return (
        <PageContainer>
            <Row>
                <Col span={24}>
                    {orderView && <>
                        <Title level={3} >业务数据 <QuestionCircleOutlined style={{ color: '#1890ff' }} onClick={() => {
                            setExplain_visible(true);
                        }} /></Title>
                        <Row className={styles.row} gutter={16}>
                            <Col span={6}>
                                <Card>
                                    <Statistic title="今日入库数" value={orderView.todayDelivery} />
                                </Card>
                            </Col>
                            <Col span={6}>
                                <Card>
                                    <Statistic title="今日出库数" value={orderView.todayPickup} />
                                </Card>
                            </Col>
                            <Col span={6}>
                                <Card>
                                    <Statistic title="今日退回数" value={orderView.todayWithdraw} />
                                </Card>
                            </Col>
                            <Col span={6}>
                                <Card>
                                    <Statistic title="当前库存量" value={orderView.currentStock} />
                                </Card>
                            </Col>
                        </Row>
                    </>}
                    {inComeView && <>
                        <Title level={3} >收入数据</Title>
                        <Row className={styles.row} gutter={16}>
                            <Col span={6}>
                                <Card>
                                    <Statistic title="今日收入总数" value={inComeView.total / 100} />
                                </Card>
                            </Col>
                            <Col span={6}>
                                <Card>
                                    <Statistic title="今日派件收入" value={inComeView.delivery / 100} />
                                </Card>
                            </Col>
                            <Col span={6}>
                                <Card>
                                    <Statistic title="今日取件收入" value={inComeView.pickup / 100} />
                                </Card>
                            </Col>
                        </Row>
                    </>}
                </Col>
                <Col span={12}>
                    {/* 通知消息 */}
                    <ProTable<API.RuleListItem, API.PageParams>
                        actionRef={actionRef}
                        rowKey="id"
                        pagination={{
                            size: 'small',
                            defaultPageSize: 10
                        }}
                        search={false}
                        options={false}
                        headerTitle={`通知中心  未读：(${unReadNum})`}
                        params={{
                            platform: 3,
                            read: readType
                        }}
                        toolBarRender={() => [
                            <Select defaultValue={0} style={{ width: 120 }} onChange={(value: number) => {
                                setReadType(value);
                                actionRef?.current?.reset && actionRef?.current?.reset();
                            }}>
                                <Option value={0}>全部</Option>
                                <Option value={1}>未读</Option>
                                <Option value={2}>已读</Option>
                            </Select>
                        ]}
                        request={async (params: any) => {
                            if (!params.startTime) { params.startTime = moment().subtract(30, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'); }
                            if (!params.endTime) { params.endTime = moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'); }
                            const msg = await getNoticeList(params);
                            return {
                                data: msg.body?.list || [],
                                success: msg.code === 0,
                                total: msg.body?.count,
                            }
                        }}
                        columns={columns}
                    />
                </Col>
            </Row>
            <Modal
                width={850}
                title={"数据说明"}
                footer={null}
                visible={explain_visible}
                onCancel={() => {
                    setExplain_visible(false);
                }}
                maskClosable={true}>
                <Descriptions bordered column={1}>
                    <Descriptions.Item label="今日入库数">系统创建订单即算入库数 </Descriptions.Item>
                    <Descriptions.Item label="今日出库数">订单变为已出库即计算出库数</Descriptions.Item>
                    <Descriptions.Item label="今日退回数">订单变为已出库即计算退回数 </Descriptions.Item>
                    <Descriptions.Item label="当前库存量">当前驿站近90天，待出库、待柜体响应、待核对手机号、待退回、移库中的订单数之和</Descriptions.Item>
                    <Descriptions.Item label="今日收入总数">当日派件收入+寄件收入之和，未绑定合作快递员，不会计算进入收入总数</Descriptions.Item>
                    <Descriptions.Item label="今日派件收入">派件收入为当日合作快递员结算成功的金额数，注意：绑定合作快递员才会计算派件收入，未绑定合作不计算</Descriptions.Item>
                    <Descriptions.Item label="今日寄件收入">与合作快递员结算后，归属驿站部分的金额，注意：绑定合作快递员才算会计算寄件收入，未绑定合作不计算</Descriptions.Item>
                </Descriptions>
            </Modal>
            <Modal
                width={850}
                title={"通知详情"}
                footer={null}
                visible={notice_visible}
                destroyOnClose={true}
                onCancel={() => {
                    getUnReadCount();
                    actionRef?.current?.reset && actionRef?.current?.reset();
                    setNotice_visible(false);
                }}
                maskClosable={true}>
                <Typography style={{ maxHeight: 600, overflowY: 'auto' }}>
                    <Title style={{ textAlign: 'center' }}>{noticeDetail?.title}</Title>
                    <Paragraph style={{ textAlign: 'center' }}>
                        <span style={{ marginRight: 20 }}>{noticeDetail?.createName}</span>
                        <span>{noticeDetail?.createTime}</span>
                    </Paragraph>
                    <Paragraph>
                        {noticeDetail?.content}
                    </Paragraph>
                    {noticeDetail?.image && <Image width={'100%'} src={noticeDetail?.image} />}
                </Typography>
            </Modal>
        </PageContainer>
    );
};

export default Index;
